const { DataTypes, where } = require("sequelize");
const sequelize = require("../config/sequelize");
const User = require("./user");
const Sports = require("./sports");
const SportsUseNum = require("./sportsusenum");

const SportsRecord = sequelize.define(
  "SportsRecord",
  {
    unit: {
      type: DataTypes.STRING,
      allowNull: false,
      defaultValue: "分钟",
      comment: "运动记录单位",
    },
    num: {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: 100,
      comment: "运动记录分钟",
    },
    totalHeat: {
      type: DataTypes.INTEGER,
      allowNull: false,
      comment: "运动记录消耗热量",
    },
    recordDate: {
      type: DataTypes.STRING,
      allowNull: false,
      comment: "饮食记录时间",
    },
  },
  {
    sequelize: sequelize,
    tableName: "sportsrecord",
    underscored: true, //显示在数据库字段为下划线
  }
);

SportsRecord.belongsTo(Sports, {
  constraints: false,
  foreignKey: "sportsId",
  as: "sports",
});
SportsRecord.belongsTo(User, {
  constraints: false,
  foreignKey: "userId",
  as: "user",
});
// 运动的使用记录加一
SportsRecord.afterCreate(async (sportsRecord) => {
  const sportsUseNum = await SportsUseNum.findOne({
    where: { sportsId: sportsRecord.sportsId, userId: sportsRecord.userId },
  });
  if (sportsUseNum) {
    await SportsUseNum.increment(
      { num: 1 },
      {
        where: { sportsId: sportsRecord.sportsId, userId: sportsRecord.userId },
      }
    );
  } else {
    await SportsUseNum.create({
      num: 1,
      sportsId: sportsRecord.sportsId,
      userId: sportsRecord.userId,
    });
  }
});

module.exports = SportsRecord;
